package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.util.Map;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.UpdateResult;

/**
 * @author li
 */
public class MongoUpdateStatement extends AbstractMongoStatement {
    private static final Logger log = Slf4j.getLogger();

    public void execute(PreparedStatement preparedStatement) {
        BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
        MongoCollection mongoCollection = this.getMongoCollection(mongoPreparedStatement);
        Map<String, Object> statementDocument = this.getStatementDocumentWithParameterValues(mongoPreparedStatement.getParameterMap());

        log.debug("execute(), statementDocument={}, sql={}, parameterMap={}", statementDocument, this.sql(), mongoPreparedStatement.getParameterMap());

        Map<String, Object> whereDocument = (Map<String, Object>) statementDocument.get(WHERE);
        Map<String, Object> updateDocument = (Map<String, Object>) statementDocument.get(UPDATE_VALUES);

        UpdateResult updateResult = mongoCollection.updateMany(new Document(whereDocument), new Document(updateDocument));
        
        mongoPreparedStatement.updateCount((int) updateResult.getModifiedCount());
    }
}